package com.yanqu.road.server.manager.activity.guagifts;

import com.yanqu.road.dao.impl.activity.guagifts.GuaGiftsDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.guagifts.GuaGiftsBroadcastData;
import com.yanqu.road.logic.activity.GuaGiftsConfig.GuaGiftsConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.GuaGiftsProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class CrossGuaGiftsActivity {
    private int activityId;

    private Map<Long, GuaGiftsBroadcastData> broadcastDataMap = new ConcurrentHashMap<>();
    private List<GuaGiftsBroadcastData> needInsertBroadcastDataList = new ArrayList<>();

    /**
     * 活动内的广播id
     */
    private AtomicLong broadcastId = new AtomicLong(1);

    public CrossGuaGiftsActivity(ActivityInfo activityInfo) {
        this.activityId = activityInfo.getActivityId();
        loadDb();
    }

    private void loadDb() {
        long validTime = DateHelper.getCurrentTime() - CrossGuaGiftsConfigMgr.getConfig(activityId).getBROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS - 10 * DateHelper.SECOND_MILLIONS;
        Map<Long, GuaGiftsBroadcastData> tempDataMap = new GuaGiftsDaoImpl().getGuaGiftsBroadcastDataMap(activityId, validTime);
        long maxBroadcastId = new GuaGiftsDaoImpl().getMaxBroadcastId(activityId);
        broadcastId.set(maxBroadcastId + 1);
        broadcastDataMap = tempDataMap;
    }


    public int getActivityId() {
        return activityId;
    }

    public void receiveBroadcastMsg(GuaGiftsProto.CrossGuaGiftsGiftBroadcastMsg resultMsg) {
        GuaGiftsBroadcastData guaBroadcastData = new GuaGiftsBroadcastData(resultMsg.getActivityId(), broadcastId.getAndIncrement());
        guaBroadcastData.setContent(resultMsg.getContent());
        guaBroadcastData.setSendUserId(resultMsg.getLeftUserId());
        guaBroadcastData.setReceiveUserId(resultMsg.getRightUserId());
        guaBroadcastData.setSendUserBaseInfo(PlayerBasePb.parseToUserBaseInfo(resultMsg.getLeftUserInfo()));
        guaBroadcastData.setReceiveUserBaseInfo(PlayerBasePb.parseToUserBaseInfo(resultMsg.getRightUserInfo()));
        guaBroadcastData.setGiftId(resultMsg.getGiftId());
        guaBroadcastData.setTime(resultMsg.getSendTime());

        synchronized (broadcastDataMap) {
            if (!broadcastDataMap.containsKey(guaBroadcastData.getBroadcastId())) {
                needInsertBroadcastDataList.add(guaBroadcastData);
            }

            broadcastDataMap.put(guaBroadcastData.getBroadcastId(), guaBroadcastData);
        }
        GuaGiftsProto.GuaGiftsGiftBroadcastMsg.Builder builder = CrossGuaGiftsMgr.parseBroadcastMsg(guaBroadcastData);

        for (Long serverId : CrossGuaGiftsConfigMgr.getConfig(activityId).getActivityInfo().getServerIdList()) {
            GuaGiftsProto.CrossGuaGiftsBroadcastBackMsg.Builder backMsg = GuaGiftsProto.CrossGuaGiftsBroadcastBackMsg.newBuilder();
            backMsg.setTargetUserId(0);
            backMsg.addBroadcastList(builder);
            MessageHelper.sendPacket(serverId, 0,
                    YanQuMessageUtils.buildMessage(GameProtocol.S_GUAGIFTS_GIFTS_BROADCAST, backMsg));
        }

    }

    public List<GuaGiftsBroadcastData> getBroadcastDataList() {
        List<GuaGiftsBroadcastData> list;
        synchronized (broadcastDataMap) {
            list = new ArrayList<>(broadcastDataMap.values());
        }
        return list;
    }

    public void loginGetBroadcastMsg(long serverId, long userId, List<Long> excludeId) {
        GuaGiftsConfig config = CrossGuaGiftsConfigMgr.getConfig(activityId);
        if (config == null) {
            return;
        }

        List<GuaGiftsBroadcastData> list = getBroadcastDataList();

        long currentTime = DateHelper.getCurrentTime();

        GuaGiftsProto.CrossGuaGiftsBroadcastBackMsg.Builder backMsg = GuaGiftsProto.CrossGuaGiftsBroadcastBackMsg.newBuilder();
        backMsg.setTargetUserId(userId);
        for (GuaGiftsBroadcastData guaBroadcastData : list) {
            if (excludeId.contains(guaBroadcastData.getBroadcastId())) {
                continue;
            }

            if (guaBroadcastData.getTime() + config.getBROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS < currentTime) {
                continue;
            }

            backMsg.addBroadcastList(CrossGuaGiftsMgr.parseBroadcastMsg(guaBroadcastData));
        }

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(GameProtocol.S_GUAGIFTS_GIFTS_BROADCAST, backMsg));
    }

    public GuaGiftsBroadcastData getBroadcastData(long broadcastId) {
        return broadcastDataMap.get(broadcastId);
    }

    public GuaGiftsProto.CrossGetBroadcastRewardRespMsg.Builder getBroadcastReward(long broadcastId) {
        GuaGiftsProto.CrossGetBroadcastRewardRespMsg.Builder builder = GuaGiftsProto.CrossGetBroadcastRewardRespMsg.newBuilder();
        builder.setRet(0);
        GuaGiftsBroadcastData broadcastData = getBroadcastData(broadcastId);
        if (broadcastData == null) {
            return builder.setRet(GameErrorCode.E_GUAGIFTS_BROADCAST_NOT_FOUND);
        }
        if (broadcastData.getTime() + CrossGuaGiftsConfigMgr.getConfig(activityId).getBROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS < DateHelper.getCurrentTime()) {
            return builder.setRet(GameErrorCode.E_GUAGIFTS_BROADCAST_OVER_TIME);
        }
        builder.setActivityId(activityId);
        builder.setGiftId(broadcastData.getGiftId());
        builder.setBroadcastId(broadcastId);

        return builder;
    }

    public List<GuaGiftsBroadcastData> popNeedInsertList() {
        List<GuaGiftsBroadcastData> list = new ArrayList<>();
        synchronized (broadcastDataMap) {
            list.addAll(needInsertBroadcastDataList);
            needInsertBroadcastDataList.clear();
        }
        return list;
    }

    public void save() {
        List<GuaGiftsBroadcastData> list = popNeedInsertList();
        new GuaGiftsDaoImpl().saveGuaGiftsBroadcastDataList(list);

        List<GuaGiftsBroadcastData> broadcastDataList = getBroadcastDataList();
        if (!broadcastDataList.isEmpty()) {
            synchronized (broadcastDataMap) {
                for (GuaGiftsBroadcastData broadcastData : broadcastDataList) {
                    if (broadcastData.getTime() + CrossGuaGiftsConfigMgr.getConfig(activityId).getBROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS < DateHelper.getCurrentTime()) {
                        broadcastDataMap.remove(broadcastData.getBroadcastId());
                    }
                }
            }
        }
    }
}
